package com.suning.sawp.member.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.dto.storeman.Category;
import com.suning.sawp.member.dao.MemExpandConversionDao;
import com.suning.sawp.member.dto.MemExpandDataOfPlaceDto;
import com.suning.sawp.member.service.MemExpandConversionService;
import com.suning.sawp.member.vo.MemExpandDataOfCateResponse;
import com.suning.sawp.member.vo.MemExpandDataOfCateVo;
import com.suning.sawp.member.vo.MemExpandDataOfEmployeeResponse;
import com.suning.sawp.member.vo.MemExpandDataOfEmployeeVo;
import com.suning.sawp.member.vo.MemExpandDataOfPlaceCateVo;
import com.suning.sawp.member.vo.MemExpandDataOfPlaceResponse;
import com.suning.sawp.member.vo.MemExpandDataOfPlaceVo;
import com.suning.sawp.member.vo.MemExpandDataOfStoreResponse;
import com.suning.sawp.member.vo.MemExpandDataOfStoreVo;
import com.suning.sawp.service.util.DJStringUtils;
import com.suning.sawp.service.util.DateUtils;

/**
 * 
 * 门店拓展转换数据服务<br>
 * 〈功能详细描述〉
 *
 * @author 15050519
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service(value = "memExpandConversionService")
public class MemExpandConversionServiceImpl implements MemExpandConversionService {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MemExpandConversionServiceImpl.class);

    /**
     * 统计Dao接口服务
     */
    @Autowired
    MemExpandConversionDao memExpandConversionDao;

    /**
     * 查询总部，大区，分公司活动下门店的销售转换数据
     */
    @Override
    public MemExpandDataOfStoreResponse queryExpandDataOfStore(Long activityId, Integer source, Integer mode) {
        LOGGER.info("queryExpandDataOfStore enter,activityId={},source={},mode={}", activityId, source, mode);
        MemExpandDataOfStoreResponse resp = new MemExpandDataOfStoreResponse();
        List<MemExpandDataOfStoreVo> list = memExpandConversionDao.queryExpandDataOfStore(activityId, source, mode);
        // 计算转换率
        if (CollectionUtils.isNotEmpty(list)) {
            for (MemExpandDataOfStoreVo data : list) {
                data.setConversionRate(DJStringUtils.calculateRateString(data.getSaleAmount(), data.getExpectSaleAmount()));
                data.setSaleAmount(calculateAmout(data.getSaleAmount()));
                data.setExpectSaleAmount(calculateAmout(data.getExpectSaleAmount()));
                data.setSingleSaleAmount(calculateAmout(data.getSingleSaleAmount()));
                data.setSuitSaleAmount(calculateAmout(data.getSuitSaleAmount()));
            }
        }
        resp.setList(list);
        LOGGER.info("queryExpandDataOfStore exit,resp={}", resp);
        return resp;
    }
    
    /**
     * 计算销售额(单位为万元)
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param amount
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private static String calculateAmout(String amount) {
        if (StringUtils.isNotBlank(amount)) {
            try {
                return DJStringUtils.divide(new BigDecimal(amount), BigDecimal.valueOf(10000L)).toString();
            } catch (Exception e) {
                LOGGER.error("calculateAmout error, amount=" + amount, e);
            }
        }
        return "0.00";
    }

    /**
     * 查询门店下八个品类的销售转换数据
     */
    @Override
    public MemExpandDataOfCateResponse queryExpandDataOfStoreCate(Long activityId, String storeCode, Integer source,
            Integer mode) {
        LOGGER.info("queryExpandDataOfStoreCate enter,activityId={},storeCode={},source={},mode={}", activityId,
                storeCode, source, mode);
        MemExpandDataOfCateResponse resp = new MemExpandDataOfCateResponse();
        List<MemExpandDataOfCateVo> list = memExpandConversionDao.queryExpandDataOfStoreCate(activityId, storeCode,
                source, mode);
        // 计算转换率
        if (CollectionUtils.isNotEmpty(list)) {
            String cateName = null;
            for (MemExpandDataOfCateVo data : list) {
                // 品类名称处理
                if (StringUtils.isBlank(data.getCateCode())) {
                    cateName = "总计";
                } else {
                    cateName = ConfigConstants.DEFAULT_CATE_MAP.get(data.getCateCode());
                }
                // 处理品类名称
                data.setCateName(StringUtils.isBlank(cateName) ? data.getCateCode() : cateName);
                data.setConversionRate(DJStringUtils.calculateRateString(data.getSaleAmount(), data.getExpectSaleAmount()));
                data.setSaleAmount(calculateAmout(data.getSaleAmount()));
                data.setExpectSaleAmount(calculateAmout(data.getExpectSaleAmount()));
                data.setSingleSaleAmount(calculateAmout(data.getSingleSaleAmount()));
                data.setSuitSaleAmount(calculateAmout(data.getSuitSaleAmount()));
            }
        }
        resp.setList(list);
        LOGGER.info("queryExpandDataOfStoreCate exit,resp={}", resp);
        return resp;
    }

    /**
     * 查询门店品类下所有员工销售转换数据
     */
    @Override
    public MemExpandDataOfEmployeeResponse queryExpandDataOfEmployee(Long activityId, String storeCode, String cateCode,
            Integer source, Integer mode) {
        LOGGER.info("queryExpandDataOfEmployee enter,activityId={},storeCode={},cateCode={},source={},mode={}",
                activityId, storeCode, cateCode, source, mode);
        MemExpandDataOfEmployeeResponse resp = new MemExpandDataOfEmployeeResponse();
        List<MemExpandDataOfEmployeeVo> list = memExpandConversionDao.queryExpandDataOfEmployee(activityId, storeCode,
                cateCode, source, mode);
        // 计算转换率
        if (CollectionUtils.isNotEmpty(list)) {
            for (MemExpandDataOfEmployeeVo data : list) {
                data.setConversionRate(DJStringUtils.calculateRateString(data.getSaleAmount(), data.getExpectSaleAmount()));
                data.setSaleAmount(calculateAmout(data.getSaleAmount()));
                data.setExpectSaleAmount(calculateAmout(data.getExpectSaleAmount()));
                data.setSingleSaleAmount(calculateAmout(data.getSingleSaleAmount()));
                data.setSuitSaleAmount(calculateAmout(data.getSuitSaleAmount()));
            }
        }
        resp.setList(list);
        LOGGER.info("queryExpandDataOfEmployee exit,resp={}", resp);
        return resp;
    }

    /**
     * 查询指定时间内门店下拓展地点的销售转换数据
     */
    @Override
    public MemExpandDataOfPlaceResponse queryExpandDataOfPlace(String storeCode, Date startDate, Date endDate, String placeName) {
        LOGGER.info("queryExpandDataOfPlace enter,startDate={},endDate={},placeName={}", startDate, endDate, placeName);
        MemExpandDataOfPlaceResponse resp = new MemExpandDataOfPlaceResponse();
        List<MemExpandDataOfPlaceDto> list = memExpandConversionDao.queryExpandDataOfPlace(storeCode, startDate, endDate,
                placeName);
        resp.setList(convertPlaceConversion(list));
        LOGGER.info("queryExpandDataOfPlace exit,resp={}", resp);
        return resp;
    }

    /**
     * 转换拓展地点销售转换数据 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param list
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<MemExpandDataOfPlaceVo> convertPlaceConversion(List<MemExpandDataOfPlaceDto> list) {
        // 数据不为空时
        if (CollectionUtils.isNotEmpty(list)) {
            List<MemExpandDataOfPlaceVo> placeList = new ArrayList<MemExpandDataOfPlaceVo>();
            MemExpandDataOfPlaceVo place;
            for (MemExpandDataOfPlaceDto dto : list) {
                place = new MemExpandDataOfPlaceVo();
                place.setPlaceName(dto.getPlace());
                place.setExpandNum(dto.getExpandNum());
                place.setCustomerNum(dto.getCustomerNum());
                place.setShoppingCustomerNum(dto.getBuyPeopleNum());
                place.setOrderNum(dto.getOrderNum());
                place.setSaleAmount(calculateAmout(dto.getBuyAmount()));
                // 计算转换率
                place.setConversionRate(DJStringUtils.calculateRateString(dto.getBuyPeopleNum(), dto.getCustomerNum()));
                place.setCates(convertPlaceCate(dto));
                placeList.add(place);
            }
            return placeList;
        }
        return Collections.emptyList();
    }

    /**
     * 处理每个拓展地点销售品类次数 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param place
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<MemExpandDataOfPlaceCateVo> convertPlaceCate(MemExpandDataOfPlaceDto place) {
        List<MemExpandDataOfPlaceCateVo> cates = new ArrayList<MemExpandDataOfPlaceCateVo>();
        MemExpandDataOfPlaceCateVo cate;
        // 空调
        if (StringUtils.isNotBlank(place.getCate1())) {
            cate = new MemExpandDataOfPlaceCateVo();
            cate.setCateCode("00001");
            cate.setCateName(ConfigConstants.DEFAULT_CATE_MAP.get("00001"));
            cate.setSaleNum(place.getCate1());
            cates.add(cate);
        }
        // 冰洗
        if (StringUtils.isNotBlank(place.getCate2())) {
            cate = new MemExpandDataOfPlaceCateVo();
            cate.setCateCode("00002");
            cate.setCateName(ConfigConstants.DEFAULT_CATE_MAP.get("00002"));
            cate.setSaleNum(place.getCate2());
            cates.add(cate);
        }
        // "00003", "黑电"
        if (StringUtils.isNotBlank(place.getCate3())) {
            cate = new MemExpandDataOfPlaceCateVo();
            cate.setCateCode("00003");
            cate.setCateName(ConfigConstants.DEFAULT_CATE_MAP.get("00003"));
            cate.setSaleNum(place.getCate3());
            cates.add(cate);
        }
        // "00004", "数码"
        if (StringUtils.isNotBlank(place.getCate4())) {
            cate = new MemExpandDataOfPlaceCateVo();
            cate.setCateCode("00004");
            cate.setCateName(ConfigConstants.DEFAULT_CATE_MAP.get("00004"));
            cate.setSaleNum(place.getCate4());
            cates.add(cate);
        }
        // "00005", "电脑"
        if (StringUtils.isNotBlank(place.getCate5())) {
            cate = new MemExpandDataOfPlaceCateVo();
            cate.setCateCode("00005");
            cate.setCateName(ConfigConstants.DEFAULT_CATE_MAP.get("00005"));
            cate.setSaleNum(place.getCate5());
            cates.add(cate);
        }
        // "00006", "通讯"
        if (StringUtils.isNotBlank(place.getCate6())) {
            cate = new MemExpandDataOfPlaceCateVo();
            cate.setCateCode("00006");
            cate.setCateName(ConfigConstants.DEFAULT_CATE_MAP.get("00006"));
            cate.setSaleNum(place.getCate6());
            cates.add(cate);
        }
        // "00007", "生活电器"
        if (StringUtils.isNotBlank(place.getCate7())) {
            cate = new MemExpandDataOfPlaceCateVo();
            cate.setCateCode("00007");
            cate.setCateName(ConfigConstants.DEFAULT_CATE_MAP.get("00007"));
            cate.setSaleNum(place.getCate7());
            cates.add(cate);
        }
        // "00013", "厨卫"
        if (StringUtils.isNotBlank(place.getCate13())) {
            cate = new MemExpandDataOfPlaceCateVo();
            cate.setCateCode("00013");
            cate.setCateName(ConfigConstants.DEFAULT_CATE_MAP.get("00013"));
            cate.setSaleNum(place.getCate13());
            cates.add(cate);
        }
        // 按照销售次数排序
        Collections.sort(cates, new Comparator<MemExpandDataOfPlaceCateVo>(){
            @Override
            public int compare(MemExpandDataOfPlaceCateVo o1, MemExpandDataOfPlaceCateVo o2) {
                // 销售数量不为空时
                if (StringUtils.isNotBlank(o2.getSaleNum()) && StringUtils.isNotBlank(o1.getSaleNum())) {
                    return DJStringUtils.bigDecimal(o2.getSaleNum()).compareTo(DJStringUtils.bigDecimal(o1.getSaleNum()));
                } else if (StringUtils.isBlank(o2.getSaleNum())) {
                    return -1;
                } else if (StringUtils.isBlank(o1.getSaleNum())) {
                    return 1;
                }
                return 0;
            }
        });
        return cates;
    }

    /**
     * 下载门店拓展转换数据
     */
    @Override
    public List<MemExpandDataOfStoreVo> downExpandDataOfStore(Long activityId, Integer source, Integer mode) {
        // 参数校验    
        if (null == activityId) {
            return Collections.emptyList();
        }
        List<MemExpandDataOfStoreVo> list = memExpandConversionDao.queryExpandDataOfStore(activityId, source, mode);
        // 计算转换率
        if (CollectionUtils.isNotEmpty(list)) {
            for (MemExpandDataOfStoreVo data : list) {
                data.setConversionRate(DJStringUtils.calculateRateString(data.getSaleAmount(), data.getExpectSaleAmount()) + "%");
                data.setSaleAmount(calculateAmout(data.getSaleAmount()));
                data.setExpectSaleAmount(calculateAmout(data.getExpectSaleAmount()));
                data.setSingleSaleAmount(calculateAmout(data.getSingleSaleAmount()));
                data.setSuitSaleAmount(calculateAmout(data.getSuitSaleAmount()));
                //来源
                if (StringUtils.isBlank(data.getMemSource())) {
                    data.setMemSource("全部");
                } else if ("1".equals(data.getMemSource())){
                    //来源 1:门店外拓；2：询价未购
                    data.setMemSource("门店外拓");
                } else if ("2".equals(data.getMemSource())){
                    //来源 1:门店外拓；2：询价未购
                    data.setMemSource("询价未购");
                } 
                // 方式
                if (StringUtils.isBlank(data.getMemMode())) {
                    data.setMemMode("全部");
                } else if ("0".equals(data.getMemMode())) {
                    // 方式：0：预充值锁定；1意向客户
                    data.setMemMode("预充值锁定");
                } else if ("1".equals(data.getMemMode())) {
                    // 方式：0：预充值锁定；1意向客户
                    data.setMemMode("意向客户");
                } 
            }
            return list;
        }
        return Collections.emptyList();
    }

    /**
     * 下载门店品类拓展转换数据
     */
    @Override
    public List<MemExpandDataOfCateVo> downExpandDataOfStoreCate(Long activityId, String storeCode, Integer source, Integer mode) {
        // 参数校验    
        if (null == activityId || StringUtils.isBlank(storeCode)) {
            return Collections.emptyList();
        }
        List<MemExpandDataOfCateVo> list = memExpandConversionDao.queryExpandDataOfStoreCate(activityId, storeCode,
                source, mode);
        // 计算转换率
        if (CollectionUtils.isNotEmpty(list)) {
            String cateName = null;
            for (MemExpandDataOfCateVo data : list) {
                // 品类名称处理
                if (StringUtils.isBlank(data.getCateCode())) {
                    cateName = "总计";
                } else {
                    cateName = ConfigConstants.DEFAULT_CATE_MAP.get(data.getCateCode());
                }
                // 处理品类名称
                data.setCateName(StringUtils.isBlank(cateName) ? data.getCateCode() : cateName);
                data.setConversionRate(DJStringUtils.calculateRateString(data.getSaleAmount(), data.getExpectSaleAmount()) + "%");
                data.setSaleAmount(calculateAmout(data.getSaleAmount()));
                data.setExpectSaleAmount(calculateAmout(data.getExpectSaleAmount()));
                data.setSingleSaleAmount(calculateAmout(data.getSingleSaleAmount()));
                data.setSuitSaleAmount(calculateAmout(data.getSuitSaleAmount()));
                //来源
                if (StringUtils.isBlank(data.getMemSource())) {
                    data.setMemSource("全部");
                } else if ("1".equals(data.getMemSource())){
                    //来源 1:门店外拓；2：询价未购
                    data.setMemSource("门店外拓");
                } else if ("2".equals(data.getMemSource())){
                    //来源 1:门店外拓；2：询价未购
                    data.setMemSource("询价未购");
                } 
                // 方式
                if (StringUtils.isBlank(data.getMemMode())) {
                    data.setMemMode("全部");
                } else if ("0".equals(data.getMemMode())) {
                    // 方式：0：预充值锁定；1意向客户
                    data.setMemMode("预充值锁定");
                } else if ("1".equals(data.getMemMode())) {
                    // 方式：0：预充值锁定；1意向客户
                    data.setMemMode("意向客户");
                } 
            }
            return list;
        }
        return Collections.emptyList();
    }

    /**
     * 下载门店品类下员工拓展转换数据
     */
    @Override
    public List<MemExpandDataOfEmployeeVo> downExpandDataOfEmployee(Long activityId, String storeCode, String cateCode, Integer source, Integer mode) {
        // 参数校验    
        if (null == activityId || StringUtils.isBlank(storeCode) || StringUtils.isBlank(cateCode)) {
            return Collections.emptyList();
        }
        List<MemExpandDataOfEmployeeVo> list = memExpandConversionDao.queryExpandDataOfEmployee(activityId, storeCode,
                cateCode, source, mode);
        // 计算转换率
        if (CollectionUtils.isNotEmpty(list)) {
            for (MemExpandDataOfEmployeeVo data : list) {
                data.setConversionRate(DJStringUtils.calculateRateString(data.getSaleAmount(), data.getExpectSaleAmount()) + "%");
                data.setSaleAmount(calculateAmout(data.getSaleAmount()));
                data.setExpectSaleAmount(calculateAmout(data.getExpectSaleAmount()));
                data.setSingleSaleAmount(calculateAmout(data.getSingleSaleAmount()));
                data.setSuitSaleAmount(calculateAmout(data.getSuitSaleAmount()));
                //来源
                if (StringUtils.isBlank(data.getMemSource())) {
                    data.setMemSource("全部");
                } else if ("1".equals(data.getMemSource())){
                    //来源 1:门店外拓；2：询价未购
                    data.setMemSource("门店外拓");
                } else if ("2".equals(data.getMemSource())){
                    //来源 1:门店外拓；2：询价未购
                    data.setMemSource("询价未购");
                } 
                // 方式
                if (StringUtils.isBlank(data.getMemMode())) {
                    data.setMemMode("全部");
                } else if ("0".equals(data.getMemMode())) {
                    // 方式：0：预充值锁定；1意向客户
                    data.setMemMode("预充值锁定");
                } else if ("1".equals(data.getMemMode())) {
                    // 方式：0：预充值锁定；1意向客户
                    data.setMemMode("意向客户");
                } 
            }
            return list;
        }
        return Collections.emptyList();
    }

    /**
     * 下载门店外拓地点拓展转换数据
     */
    @Override
    public List<MemExpandDataOfPlaceVo> downExpandDataOfPlace(String storeCode, String startDate, String endDate, String placeName) {
        // 参数校验
        if (StringUtils.isBlank(storeCode) || StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            return Collections.emptyList();
        }
        Date startTime = null;
        Date endTime = null;
        // 格式化时间格式
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            startTime = sdf.parse(startDate);
            endTime = sdf.parse(endDate);
        } catch (Exception e) {
            LOGGER.error("queryExpandDataOfPlace error,startDate:" + startDate + ",endDate:" + endDate, e);
            return Collections.emptyList();
        }
        List<MemExpandDataOfPlaceDto> list = memExpandConversionDao.queryExpandDataOfPlace(storeCode, startTime, endTime,
                placeName);
        if (CollectionUtils.isNotEmpty(list)) {
            List<MemExpandDataOfPlaceVo> placeList = new ArrayList<MemExpandDataOfPlaceVo>();
            MemExpandDataOfPlaceVo place;
            for (MemExpandDataOfPlaceDto dto : list) {
                place = new MemExpandDataOfPlaceVo();
                place.setPlaceName(dto.getPlace());
                place.setExpandNum(dto.getExpandNum());
                place.setCustomerNum(dto.getCustomerNum());
                place.setShoppingCustomerNum(dto.getBuyPeopleNum());
                place.setOrderNum(dto.getOrderNum());
                place.setSaleAmount(calculateAmout(dto.getBuyAmount()));
                // 计算转换率
                place.setConversionRate(DJStringUtils.calculateRateString(dto.getBuyPeopleNum(), dto.getCustomerNum()) + "%");
                StringBuilder cates = new StringBuilder();
                for (MemExpandDataOfPlaceCateVo cate : convertPlaceCate(dto)) {
                    cates.append(cate.getCateName()).append(cate.getSaleNum()).append("  ");
                }
                place.setCateStrs(cates.toString());
                placeList.add(place);
            }
            return placeList;
        }
        return Collections.emptyList();
    }

    /**
     * 处理销售转换数据
     */
    @Override
    public void processExpandConversionData(String endDate) throws ParseException {
        LOGGER.info("processExpandConversionData, endDate= {}", endDate);
        Date endTime = null;
        if (StringUtils.isNotBlank(endDate)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            endTime = sdf.parse(endDate);
        } else {
            // 取昨天的时间
            endTime = DateUtils.getNowDateShort("yyyy-MM-dd", -1);
        }
        LOGGER.info("processExpandConversionData, endTime= {}", endTime);
        memExpandConversionDao.processExpandConversionData(endTime);
    }

    /**
     * 查询门店拓展品类
     */
    @Override
    public List<Category> queryActivityStoreCategorys(Long activityId, String storeCode) {
        return memExpandConversionDao.queryActivityStoreCategorys(activityId, storeCode);
    }

}
